<template>
<h1>详情页面</h1>
  <h1>{{weibo.nickname}}说了:{{weibo.content}}</h1>
  <p>发布与:{{weibo.created}}</p>
  <hr>
  <el-input v-model="comment.content" placeholder="请留下你的评论吧!"></el-input>
  <el-button type="primary" @click="post()" style="margin: 10px;">发布评论</el-button>
  <div v-for="c in arr">
    <h4>{{c.nickname}}评论说:{{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
import router from "@/router";

const weibo=ref({});
onMounted(()=>{
  //获取地址栏url中的参数值
  //http://localhost:9090/deta?id=209
  //location.search就是url中查询字符串id=209
  let id=new URLSearchParams(location.search).get('id');
  axios.get('http://localhost:8080/v1/weibos/'+id+'/detail').then((response)=>{
    if (response.data.code==2002){
      weibo.value=response.data.data;
    }
  })
})
const comment=ref({content:''});
const post=()=>{
  //获取user数据
  let user=getUser();
  //如果没有获取到user数据,就让用户登录
  if(user==null){
    ElMessage.error('请先登录!');
    router.push('/login');
    return;
  }
  //给评论对象设置评论员与微博id
  comment.value.userId=user.id;
  comment.value.weiboId=weibo.value.id;
  let data=qs.stringify(comment.value);
  axios.post('http://localhost:8080/v1/comments/add-new',data).then((response)=>{
    if (response.data.code==2002){
      ElMessage.success('评论成功!');
      //评论成功后,需要立即加载评论
      loadComments(weibo.value.id);
    }
  })
}
//定义响应式变量arr保存评论数据
const arr=ref([]);
//定义加载评论的函数,参数是当前微博的id
const loadComments=(id)=>{
  //给后端发请求,查这条微博的评论
axios.get('http://localhost:8080/v1/comments/'+id).then((response)=>{
  if (response.data.code==2002){
    arr.value=response.data.data;
  }
})
}


</script>

<style scoped>

</style>